package file

import (
	"myserver/app/service/file_service"
	"myserver/app/types"
	"myserver/pkg/constant"
	"net/http"
	"strings"

	pkgApp "myserver/pkg/app"

	"github.com/gin-gonic/gin"
)

type UploadFileController struct{}

func (UploadFileController) UploadFile(c *gin.Context) {
	file, header, err := c.Request.FormFile("file")
	var (
		app = pkgApp.Gin{C: c}
	)
	if err != nil {
		app.Response(http.StatusInternalServerError, "请上传文件", nil)
		return
	}
	Filename := header.Filename
	size := header.Size
	se := file_service.FileService{File: &file, Filename: Filename, Size: size}
	uuid, err := se.Save()
	if err != nil {
		app.Response(http.StatusInternalServerError, "上传失败", nil)
		return
	}
	app.Response(http.StatusOK, constant.SUCCESS, uuid)
}
func (UploadFileController) GetFile(c *gin.Context) {
	var (
		m     = types.SysFile{}
		app   = pkgApp.Gin{C: c}
		uuids []string
	)
	pkgApp.BindAndValid(c, &m)
	if m.Uuid == "" {
		app.Response(http.StatusInternalServerError, "请传入fileKey", nil)
		return
	}
	uuids = append(uuids, m.Uuid)
	se := file_service.FileService{}
	s, name, err := se.GetFile(uuids)
	if err != nil {
		app.Response(http.StatusInternalServerError, err.Error(), nil)
		return
	}
	c.Header("Content-Description", "File Transfer")
	c.Header("Content-Transfer-Encoding", "binary")
	c.Header("Content-Disposition", "attachment; filename="+name)
	c.Header("Content-Type", "application/octet-stream")
	c.String(http.StatusOK, s)

}

func (UploadFileController) List(c *gin.Context) {
	var (
		m    = types.FileListStruct{}
		app  = pkgApp.Gin{C: c}
		data = types.FileListResponse{}
	)
	httpCode, errCode, err := pkgApp.BindAndValid(c, &m)
	if err != nil {
		app.Response(httpCode, errCode, err.Error())
		return
	}
	if m.Page == 0 {
		app.Response(http.StatusInternalServerError, "page不能为0", nil)
		return
	}
	if m.Size <= 0 {
		app.Response(http.StatusInternalServerError, "size必须大于0", nil)
		return
	}
	se := file_service.FileService{}
	ls, count, err := se.List(m.Page, m.Size, m.KeyWords)

	if err != nil {
		app.Response(http.StatusInternalServerError, err.Error(), nil)
		return
	}
	ls1, err := pkgApp.ConvertDataByArr[types.SysFile](ls)
	if err != nil {
		app.Response(http.StatusInternalServerError, err.Error(), nil)
		return
	}
	data.List = ls1
	data.Total = count
	app.Response(http.StatusOK, constant.SUCCESS, data)
}

type DellFileStruct struct {
	UuIds string `json:"uuids" form:"uuids" binding:"required"`
}

func (UploadFileController) DellFile(c *gin.Context) {
	var (
		m   = DellFileStruct{}
		app = pkgApp.Gin{C: c}
	)
	httpCode, errCode, err := pkgApp.BindAndValid(c, &m)
	if err != nil {
		app.Response(httpCode, errCode, err.Error())
		return
	}
	uuids := strings.Split(m.UuIds, ",")
	se := file_service.FileService{}
	err = se.DellFile(uuids)
	if err != nil {
		app.Response(http.StatusInternalServerError, err.Error(), nil)
		return
	}
	app.Response(http.StatusOK, constant.SUCCESS, nil)
}
